/**
 * Created by guo.xiaomin on 2017-09-21.
 */
var moment = require('moment');
var messageUtil = require('../common/utils/messageUtil');
var mtOrderService = require('../services/mtOrderService');
var nodeExcel = require('excel-export');
var toolUtil = require('../common/utils/toolUtil');

exports.mtOrderSchedule = function (req, res) {

    mtOrderService.mtOrderSchedule(function(err, results) {
        if (err) {
            logger.error('Failed to mtOrderSchedule ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, ''));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, ''));
        }
    });


};

exports.refundStatusFor66ByStartEndDate = function (req, res) {
    //手动获取每天美囤订单信息
    var fromDateSelect = req.body.fromDateSelect;
    var toDateSelect = req.body.toDateSelect;

    mtOrderService.refundStatusFor66ByStartEndDate(fromDateSelect, toDateSelect,  function(err, results) {
        if (err) {
            logger.error('Failed to refundStatusFor66ByStartEndDate ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, ''));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results, ''));
        }
    });
};

exports.manualmtOrderSchedule = function (req, res) {
    //手动获取每天美囤订单信息
    var startDateSelect = req.body.startDateSelect;
    var today = new Date(moment(startDateSelect, "YYYY-MM-DD").format());
    var tomorrow = new Date(moment(startDateSelect, "YYYY-MM-DD").add(1, "days").subtract(1, 'seconds').format("YYYY-MM-DD hh:mm:ss a"));
    mtOrderService.getNextVersionByDbName("mt_order_check_log", function(err, version){
        mtOrderService.getMtOrderByStartEndDate(today.getTime(), tomorrow.getTime(), today, tomorrow, 1, version, false, function(err, results) {
            if (err) {
                logger.error('Failed to getMtOrderByStartEndDate ---' + err.message);
                res.json(messageUtil.composeFailedMessage(req, err.message, ''));
            } else {
                res.json(messageUtil.composeSucceededMessage(req, null, results, ''));
            }
        });
    });
};

exports.manualmtOrderScheduleFromTo = function (req, res) {
    //手动获取每天美囤订单信息
    var fromDateSelect = req.body.fromDateSelect;
    var toDateSelect = req.body.toDateSelect;

    mtOrderService.getMtOrderByStartEndDateFromTo(fromDateSelect, toDateSelect,  function(err, results) {
        if (err) {
            logger.error('Failed to getMtOrderByStartEndDate ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, ''));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results, ''));
        }
    });
};

// 粗算
exports.manualmtOrderScheduleFromToRough = function (req, res) {
    //手动获取每天美囤订单信息
    var fromDateSelect = req.body.fromDateSelect;
    var toDateSelect = req.body.toDateSelect;

    mtOrderService.getMtOrderByStartEndDateFromToRough(fromDateSelect, toDateSelect,  function(err, results) {
        if (err) {
            logger.error('Failed to manualmtOrderScheduleFromToRough ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, ''));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results, ''));
        }
    });
};

// 复核
exports.manualmtOrderScheduleFromToCheck = function (req, res) {
    //手动获取每天美囤订单信息
    var fromDateSelect = req.body.fromDateSelect;
    var toDateSelect = req.body.toDateSelect;

    mtOrderService.getMtOrderByStartEndDateFromToCheck(fromDateSelect, toDateSelect,  function(err, results) {
        if (err) {
            logger.error('Failed to manualmtOrderScheduleFromToRough ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, ''));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results, ''));
        }
    });
};

// 精算
exports.manualmtOrderScheduleFromToActuary = function (req, res) {
    //手动获取每天美囤订单信息
    var fromDateSelect = req.body.fromDateSelect;
    var toDateSelect = req.body.toDateSelect;

    mtOrderService.getMtOrderByStartEndDateFromToActuary(fromDateSelect, toDateSelect,  function(err, results) {
        if (err) {
            logger.error('Failed to manualmtOrderScheduleFromToRough ---' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, ''));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, results, ''));
        }
    });
};

exports.communityAmbassadordataShow = function(req, res) {
    //小区大使业绩信息显示
    mtOrderService.communityAmbassadordataShow(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when questionList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionList...'));
        }else {
            var dataresult=results[1];
            var rdata=[];
            for(var i = 0 ; i<dataresult.length;i++ ){
                var tt1="";
                if(dataresult[i]){
                    tt1=dataresult[i]._doc ;
                }
                var tt2=dataresult[i].user;
                var tt3=new Object();
                // 下单日期格式化
                if(tt1 && tt1.order_time) {
                    tt1.order_time = moment(tt1.order_time).format('YYYY-MM-DD HH:mm:ss');
                }
                if(tt2 && tt2[0]){
                tt3.unickName=tt2[0]._doc.nickName;
                tt3.umobilePhone=tt2[0]._doc.mobilePhone;
                }else{
                    tt3.unickName="";
                    tt3.umobilePhone="";
                }
                if(dataresult[i].count){
                    tt3.count=dataresult[i].count;
                }else{
                    tt3.count="";
                }
                if(dataresult[i].city && dataresult[i].city[0]){
                    tt3.cityName=dataresult[i].city[0]._doc.name;
                }else{
                    tt3.cityName="";
                }
                if(dataresult[i].community && dataresult[i].community && dataresult[i].community[0]){
                    tt3.communityName=dataresult[i].community[0].communityName;
                }else{
                    tt3.communityName="";
                }
                var obj = Object.assign(tt1, tt3);
                rdata.push(obj);
            }
            var data = {
                count: results[0]["count"],
                totalPage: results[0]["page"],
                //list: results[1]
                list: rdata
            };
            //logger.debug('data: ');
            //logger.debug(data);
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};

exports.communityAmbassadordataExport = function (req,res){
    //小区大使信息导出
    mtOrderService.communityAmbassadordataExportsData(req, function(err, results) {
        if (err) {
            logger.error('Exception happen when exportUser...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when exporUser...'));
        } else {
            if(!results[1]) {
                logger.error('Exception happen when exporUserScore...导出数据为0' + err.message);
                res.json(messageUtil.composeSucceededMessage(req, null, {}));
            }else {
                var conf={};
                conf.cols= [{
                    caption: '类别',
                    // caption: '类目（国内自营、国内标品、海淘标品、海淘非标品、国内非标品）',
                    type: 'string'
                },{
                    // caption: '订单号',
                    caption: '订单ID',
                    type: 'string'
                },{
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 start */
                    caption: '结算状态',
                    type: 'string'
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 end */
                },{
                    caption: '订单类型',
                    type: 'string'
                },
                // {
                //     caption: 'member_id',
                //     type: 'string'
                // },
                    {
                    caption: '下单日期时间',
                    type: 'string'
                },{
                    caption: '链接发起人UID',
                    type: 'string'
                },{
                    caption: '链接发起人昵称',
                    type: 'string'
                },{
                    caption: '链接发起人手机号码',
                    type: 'string'
                },{
                    caption: '链接发起人是否是小区大使',
                    type: 'string'
                },{
                    caption: '购买用户UID',
                    type: 'string'
                },{
                    caption: '购买用户昵称',
                    type: 'string'
                },{
                    caption: '购买用户手机号码',
                    type: 'string'
                },{
                    caption: '购买用户所在城市',
                    type: 'string'
                },{
                    caption: '购买用户所在小区',
                    type: 'string'
                },{
                    caption: '购买用户所在小区人数',
                    type: 'string'
                },{
                    caption: '购买用户所在小区小区大使昵称',
                    type: 'string'
                },{
                    caption: '购买用户所在小区小区大使手机号码',
                    type: 'string'
                },{
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 start */
                    caption: '商品单价',
                    type: 'string'
                },{
                    caption: '商品数量',
                    type: 'number'
                },{
                    caption: '订单优惠总价',
                    type: 'number'
                },{
                    caption: '商品类目佣金比例',
                    type: 'number'
                },{
                    caption: '订单佣金',
                    type: 'number'
                },{
                    caption: '分成比例',
                    type: 'number'
                },
                // {
                //     caption: '订单金额',
                //     type: 'number'
                // },{
                //     caption: '订单数量',
                //     type: 'number'
                // },{
                //     caption: '拼团活动价',
                //     type: 'number'
                // },
                /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 end */
                {
                    caption: 'sku_code',
                    type: 'string'
                },{
                    caption: 'sku_name',
                    type: 'string'
                },{
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 start */
                    caption: '订单状态',
                    type: 'string'
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 end */
                }];
                var dataresult=results[1];
                var data=[];
                for(var i = 0 ; i<dataresult.length;i++ ){
                    var tt1="";
                    if(dataresult[i]){
                        tt1=dataresult[i]._doc ;
                    }
                    var tt2=dataresult[i].user;
                    var tt3=new Object();
                    if(tt2 && tt2[0]){
                        tt3.unickName=tt2[0]._doc.nickName;
                        tt3.umobilePhone=tt2[0]._doc.mobilePhone;
                    }else{
                        tt3.unickName="";
                        tt3.umobilePhone="";
                    }
                    if(dataresult[i].count){
                        tt3.count=dataresult[i].count;
                    }else{
                        tt3.count="";
                    }
                    if(dataresult[i].city && dataresult[i].city[0]){
                        tt3.cityName=dataresult[i].city[0]._doc.name;
                    }else{
                        tt3.cityName="";
                    }
                    if(dataresult[i].community && dataresult[i].community && dataresult[i].community[0]){
                        tt3.communityName=dataresult[i].community[0].communityName;
                    }else{
                        tt3.communityName="";
                    }
                    var obj = Object.assign(tt1, tt3);
                    data.push(obj);
                }
                //var data = results[1];
                var tempRow=[];
                for(var i = 0 ;i<data.length ;i++ ){
                    var temp=[];
                    var one="";
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 start */
                    if(data[i].itemSaleType){
                        var itemSaleTypeName = toolUtil.getItemSaleTypeName(data[i].itemSaleType);
                        one = itemSaleTypeName;
                    }else{
                        if (data[i].itemSaleType == 0) {
                            var itemSaleTypeName = toolUtil.getItemSaleTypeName(data[i].itemSaleType);
                            one = itemSaleTypeName;
                        } else {
                            one+="";
                        }
                    }
                    if(data[i].wavesSign){
                        var wavesSignName = toolUtil.getWavesSignName(data[i].wavesSign);
                        one += " " + wavesSignName;
                    }else{
                        if (data[i].wavesSign == 0) {
                            var wavesSignName = toolUtil.getWavesSignName(data[i].wavesSign);
                            one += " " + wavesSignName;
                        } else {
                            one += " ";
                        }
                    }
                    if(data[i].standard){
                        var standardName = toolUtil.getStandardName(data[i].standard);
                        one += " " + standardName;
                    }else{
                        if (data[i].standard == 0) {
                            var standardName = toolUtil.getStandardName(data[i].standard);
                            one += " " + standardName;
                        } else {
                            one += " ";
                        }
                    }
                    temp.push(one);
                    // if(one){
                    //     temp.push(one);
                    // }
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 end */
                    if(data[i].order_id){
                        temp.push(data[i].order_id);
                    }else{
                        temp.push("");
                    }
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 start */
                    // 结算状态
                    if (data[i].balanceStatus) {
                        var balanceStatusName = toolUtil.getNameByBalanceStatus(data[i].balanceStatus);
                        temp.push(balanceStatusName);
                    } else {
                        if (data[i].balanceStatus == 0) {
                            var balanceStatusName = toolUtil.getNameByBalanceStatus(data[i].balanceStatus);
                            temp.push(balanceStatusName);
                        } else {
                            temp.push("");
                        }
                    }
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 end */
                    // 订单类型-start
                    var shareCommissionUser = data[i].shareCommissionUser;
                    var selfPurchaseUser = data[i].selfPurchaseUser;
                    var communityCommissionUser = data[i].communityCommissionUser;
                    var inviterCommissionUser = data[i].inviterCommissionUser;

                    temp.push(toolUtil.getShareSelfCommunityInviterType(shareCommissionUser, selfPurchaseUser, communityCommissionUser, inviterCommissionUser));
                    // 订单类型-end
                    // if(data[i].member_id){
                    //     temp.push(data[i].member_id);
                    // }else{
                    //     temp.push("");
                    // }
                    if(data[i].order_time){
                        // HH 24小时制，hh12小时制
                        temp.push(moment(data[i].order_time).format('YYYY-MM-DD HH:mm:ss'));
                    }else{
                        temp.push("");
                    }
                    if(data[i].share_user && data[i].share_user._doc.encUserId){
                        temp.push(data[i].share_user._doc.encUserId);
                    }else{
                        temp.push("");
                    }
                    if(data[i].share_user && data[i].share_user.nickName){
                        temp.push(data[i].share_user.nickName);
                    }else{
                        temp.push("");
                    }
                    if(data[i].share_uhp){
                        temp.push(data[i].share_uhp);
                    }else{
                        temp.push("");
                    }
                    if(data[i].is_share_moderator){
                        if(data[i].is_share_moderator){
                            temp.push("是");
                        }
                    }else{
                        temp.push("否");
                    }
                    if(data[i].order_user && data[i].order_user._doc.encUserId){
                        temp.push(data[i].order_user._doc.encUserId);
                    }else{
                        temp.push("");
                    }
                    if(data[i].order_user && data[i].order_user._doc.nickName){
                        temp.push(data[i].order_user._doc.nickName);
                    }else{
                        temp.push("");
                    }
                    if(data[i].order_uhp){
                        temp.push(data[i].order_uhp);
                    }else{
                        temp.push("");
                    }
                    if(data[i].cityName){
                        temp.push(data[i].cityName);
                    }else{
                        temp.push("");
                    }
                    if(data[i].communityName){
                        temp.push(data[i].communityName);
                    }else{
                        temp.push("");
                    }
                    if(data[i].count){
                        temp.push(data[i].count.toString());
                    }else{
                        temp.push("");
                    }
                    if(data[i].unickName){
                        temp.push(data[i].unickName);
                    }else{
                        temp.push("");
                    }
                    if(data[i].umobilePhone){
                        temp.push(data[i].umobilePhone);
                    }else{
                        temp.push("");
                    }
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 start */
                    // 商品单价
                    if (data[i].price) {
                        temp.push(data[i].price.toString());
                    } else {
                        temp.push("");
                    }
                    // 商品数量
                    if (data[i].skuQuantity) {
                        temp.push(data[i].skuQuantity.toString());
                    } else {
                        temp.push("");
                    }
                    // 订单优惠总价
                    if (data[i].skuSubTotal) {
                        temp.push(data[i].skuSubTotal.toString());
                    } else {
                        temp.push("");
                    }
                    // 商品类目佣金比例
                    if (data[i].commissionPercent) {
                        temp.push(data[i].commissionPercent.toString())
                    } else {
                        if (data[i].commissionPercent == 0) {
                            temp.push(data[i].commissionPercent.toString())
                        } else {
                            temp.push("");
                        }
                    }
                    // 订单佣金
                    var orderComm = 0;
                    if (data[i].shareCommission) {
                        orderComm += data[i].shareCommission;
                    } else if (data[i].selfPurchase) {
                        orderComm += data[i].selfPurchase;
                    } else if (data[i].communityCommission) {
                        orderComm += data[i].communityCommission;
                    } else if (data[i].inviterCommission) {
                        orderComm += data[i].inviterCommission;
                    }
                    if (orderComm) {
                        temp.push(orderComm.toString());
                    } else {
                        if (orderComm == 0 && data[i].commissionPercent != 0 && data[i].skuSubTotal) {
                            temp.push("");
                            // temp.push(data[i].comment.toString());
                        } else {
                            temp.push(orderComm.toString())
                        }
                    }
                    // 分成比例
                    if (data[i].commissionDrawPercentage) {
                        temp.push(data[i].commissionDrawPercentage.toString());
                    } else {
                        temp.push("");
                    }
                    // if(data[i].total){
                    //     temp.push(data[i].total);
                    // }else{
                    //     temp.push("");
                    // }
                    // if(data[i].quantity){
                    //     //console.log("data[i].quantity;"+data[i].quantity);
                    //     temp.push(data[i].quantity);
                    // }else{
                    //     temp.push("");
                    // }
                    // if(data[i].total&&data[i].quantity){
                    //     var price=data[i].total/data[i].quantity;
                    //     temp.push(price);
                    // }else{
                    //     temp.push("");
                    // }
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 end */
                    if(data[i].sku_code){
                        temp.push(data[i].sku_code);
                    }else{
                        temp.push("");
                    }
                    if(data[i].sku_name){
                        temp.push(data[i].sku_name);
                    }else{
                        temp.push("");
                    }
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 start */
                    // 订单状态
                    if (data[i].status) {
                        var statusName = toolUtil.getNameByStatus(data[i].status);
                        temp.push(statusName);
                    } else {
                        if (data[i].status == 0) {
                            var statusName = toolUtil.getNameByStatus(data[i].status);
                            temp.push(statusName);
                        } else {
                            temp.push("");
                        }
                    }
                    /* 宝宝树66小区 sprint6 小区大使业绩页面 导出小区大使业绩追加结算状态等字段 add wangcan 20171205 end */

                    tempRow.push(temp);
                }
                var body=req.cparams;
                var filename="Order:".toString()+body.startDate.substring(0,10).toString()+"---".toString()+body.endDate.substring(0,10).toString()+".xlsx";
                conf.rows=tempRow;
                var ret = nodeExcel.execute(conf);
                res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                //res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
                res.setHeader("Content-Disposition", "attachment; filename=" + filename);
                res.end(ret, 'binary');
            }
        }
    })
}

exports.communityAmbassadordataShowApp = function(req, res) {
    //小区大使业绩信息显示
    mtOrderService.communityAmbassadordataShowApp(req, function(err, results) {

        if (err) {
            logger.error('Exception happen when questionList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when questionList...'));
        }else {
            res.json(messageUtil.composeSucceededMessage(req, null, results));
        }

    });
};
